#include "texturemanager.h"
#include <list>

std::list<CTexture *> g_textures;

//===============================================================
// Loads a texture from the specified file.
//===============================================================
CTexture *CTextureManager::Load(const char *szFileName)
{
	CTexture *pTex = Get(szFileName); /* Check if the texture is already loaded. */
	if (pTex)
		return pTex;


	GLuint nTexture;
	ILuint nILImage;

	ilGenImages(1, &nILImage);
	ilBindImage(nILImage);

	/* Load the image and convert it to a OpenGL texture. */
	ILboolean nResult = ilLoadImage(szFileName);
	if (nResult)
	{
		nResult = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
		if (!nResult) 
			return NULL;

		glGenTextures(1, &nTexture);
		glBindTexture(GL_TEXTURE_2D, nTexture);

		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 

		glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE, ilGetData());
	}
	else return NULL;

	pTex = new CTexture(szFileName, nTexture, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT));
	g_textures.push_back(pTex);

	/* Texture has been loaded by OpenGL, release it now. */
	ilDeleteImages(1, &nILImage);


	return pTex;
}

//===============================================================
// Gets the texture with the specified name.
//===============================================================
CTexture *CTextureManager::Get(const char *szFileName)
{
	std::list<CTexture *>::iterator it;
	for (it = g_textures.begin(); it != g_textures.end(); it++)
	{
		if (stricmp((*it)->GetName(), szFileName) == 0)
			return *it;
	}
	return NULL;
}
